#ifdef _WIN32 
#include <windows.h> 
#endif

#include "LuaScript.h"

namespace LuaScript
{
LuaScript::LuaScript()
{
	// Create a new lua state
	LuaState = luaL_newstate();

	// Connect LuaBind to this lua state
	luabind::open(LuaState);
	luaL_openlibs(LuaState);

	table = luabind::newtable(LuaState);

	loadingOK = false;
}

LuaScript::~LuaScript(void)
{
	//lua_close(LuaState);
}

void LuaScript::pushLuaTable()
{
	luabind::globals(LuaState)[LUA_EXTERN] = table;
}

int LuaScript::initScript(std::string filename)
{
	int s = 0;

	s = loadScript(Engine::fileStructure.scriptPath + filename);

	if (s == 0)
	{
		// file found
		// binding class members
		bindClass();
		loadingOK = true;
	}
	else
	{
		std::cerr << "LUA: " << lua_tostring(LuaState, -1) << std::endl;
	}

	return s;
}

void LuaScript::_init()
{
	if (!loadingOK)
	{
		std::cerr << "LUA: Can't call _init function" << std::endl;
		return;
	}

	/* the function name */
	luabind::call_function<void>(LuaState, LUA_INIT);
}

void LuaScript::_update()
{
	if (!loadingOK)
	{
		std::cerr << "LUA: Can't call _init function" << std::endl;
		return;
	}

	/* the function name */
	luabind::call_function<void>(LuaState, LUA_UPDATE);
}

void LuaScript::_clean()
{
	if (!loadingOK)
	{
		std::cerr << "LUA: Can't call _clean function" << std::endl;
		return;
	}

	/* the function name */
	luabind::call_function<void>(LuaState, LUA_CLEAN);
}

int LuaScript::loadScript(std::string filename)
{
#ifdef _DEBUG
	std::cout << "LUA: Loading file: " << filename << std::endl;
#endif
	return luaL_dofile(LuaState, filename.c_str());
}

void LuaScript::bindClass()
{
	// override this function in child
	// binding specific class members and push it to lua API
}

lua_State * LuaScript::getLuaState()
{
	return LuaState;
}

void LuaScript::setLuaState(lua_State *state)
{
	this->LuaState = state;
}

luabind::object * LuaScript::getTable()
{
	return &table;
}

}
